<script setup>
import { ref, watch } from 'vue';
import Axios from '@/plugins/axios';

import store from '@/store';
import { difficultyOptions } from '@/plugins/consts';
import ProblemTable from '@/components/ProblemTable.vue';
import { useRoute } from 'vue-router';
import { BookmarksOutline, AddOutline } from '@vicons/ionicons5';
import { _writeSearchToQuery } from '@/plugins/utils';

const route = useRoute();

const tagsOptions = ref([]);

Axios.get('/problem/tag/').then(res => {
  tagsOptions.value = res.map(item => ({
    label: item.name,
    value: item.id,
  }));
});

const pagination = ref({ pageSize: 20, page: 1, count: 0 }),
  search = ref({
    search: '',
    difficulty: null,
    tags: [],
  }),
  data = ref([]),
  loading = ref(false);
const writeSearchToQuery = _writeSearchToQuery(
  search.value,
  pagination.value,
  route
);

const handleQueryChange = () => {
  if (!route.name === 'problem_list') return;

  search.value.search = route.query.search || '';
  search.value.difficulty =
    (route.query.difficulty && parseInt(route.query.difficulty)) || null;
  const tags = [];
  if (route.query.tags) {
    for (const tag of route.query.tags.split(',')) {
      tags.push(parseInt(tag));
    }
  }
  search.value.tags = tags;
  for (const key in pagination.value) {
    if (route.query[key]) pagination.value[key] = parseInt(route.query[key]);
  }

  loading.value = true;
  Axios.get('/problem/', {
    params: {
      limit: pagination.value.pageSize,
      offset: (pagination.value.page - 1) * pagination.value.pageSize,
      search: search.value.search,
      difficulty: search.value.difficulty,
      tags: search.value.tags.join(','),
    },
  })
    .then(res => {
      pagination.value.count = res.count;
      data.value = res.results;
    })
    .finally(() => {
      loading.value = false;
    });
};

watch(() => route.query, handleQueryChange);
handleQueryChange();
</script>

<template>
  <n-layout>
    <h1>题目列表</h1>
    <n-layout-content>
      <div style="display: inline-block">
        <n-form inline>
          <n-form-item label="题目ID/名称">
            <n-input
              v-model:value="search.search"
              @keydown.enter="writeSearchToQuery"
            />
          </n-form-item>
          <n-form-item label="题目标签">
            <n-select
              v-model:value="search.tags"
              :options="tagsOptions"
              clearable
              filterable
              multiple
              placeholder="请选择标签"
              style="min-width: 150px"
              :max-tag-count="1"
              :disabled="!tagsOptions.length"
            />
          </n-form-item>
          <n-form-item label="题目难度">
            <n-select
              v-model:value="search.difficulty"
              :options="
                [{ label: '全部', value: null }].concat(difficultyOptions)
              "
              placeholder="请选择难度"
              style="min-width: 150px"
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="writeSearchToQuery">
              搜索
            </n-button>
          </n-form-item>
        </n-form>
      </div>
      <router-link
        :to="{ name: 'tag_edit' }"
        v-if="store.state.user.permissions.includes('problem')"
      >
        <n-button style="float: right; margin-top: 25px" type="primary">
          <template #icon>
            <n-icon :component="BookmarksOutline" />
          </template>
          标签管理
        </n-button>
      </router-link>
      <router-link
        :to="{ name: 'problem_create' }"
        v-if="store.state.user.permissions.includes('problem')"
      >
        <n-button
          style="float: right; margin-top: 25px; margin-right: 10px"
          type="primary"
        >
          <template #icon>
            <n-icon :component="AddOutline" />
          </template>
          创建题目
        </n-button>
      </router-link>
    </n-layout-content>
    <n-layout-content>
      <ProblemTable :data="data" :loading="loading" />
    </n-layout-content>
    <n-layout-content>
      <div style="margin-top: 30px; text-align: center">
        <n-pagination
          v-model:page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :item-count="pagination.count"
          show-size-picker
          show-quick-jumper
          :page-sizes="[10, 20, 50]"
          @update:page="writeSearchToQuery"
          @update:page-size="
            pageSize => {
              pagination.pageSize = pageSize;
              pagination.page = 1;
              writeSearchToQuery();
            }
          "
        />
      </div>
    </n-layout-content>
  </n-layout>
</template>
